<template>
  <div class="container">
    <div class="left-section">
      <div>
        <a-tabs
            v-model:activeKey="activeKey"
            :tab-position="mode"
            :style="{ height: '50px',width:'900px'}"
            @change="changeType"
        >
          <a-tab-pane  v-for="type in types" :key="type.code" :tab="`${type.name}`"></a-tab-pane>
        </a-tabs>
        <div style="display: flex;flex-direction: row">
          类型：<a-tag  @close="removeSelectedType(selected.name)" v-for="selected in selectedType">{{selected.name}}</a-tag>
          题目：<a-input-search
            v-model:value="title"
            placeholder="input search text"
            style="width: 200px"
            @search="queryDataByCondition({pageSize:10,pageNo:1})"
        />
        </div>
      </div>
      <a-table
          :columns="columns"
          :data-source="dataSource"
          :pagination="pagination"
          @change="handleTableChange"
      >
        <template #bodyCell="{ column, text ,index}">
          <template v-if="column.dataIndex === 'title'">
            <a @click="getQuestionInfo(index)">{{ text }}</a>
          </template>
          <template v-if="column.dataIndex === 'difficulty'">
            <div :class="getDifficultyColor(text)">{{ text }}</div>
          </template>
        </template>

      </a-table>
    </div>
    <div class="right-section">
      <div class="elevated-box">
        <a-calendar  :fullscreen="false" @panelChange="onPanelChange" :key="calendarKey">
          <template #headerRender="{ value: current, type, onChange, onTypeChange }">
            <div style="padding: 10px">
              <div style="margin-bottom: 10px">每日一题</div>
              <a-row type="flex" justify="space-between">
                <a-col>
                  <a-radio-group size="small" :value="type" @change="e => onTypeChange(e.target.value)">
                    <a-radio-button value="month">Month</a-radio-button>
                    <a-radio-button value="year">Year</a-radio-button>
                  </a-radio-group>
                </a-col>
                <a-col>
                  <a-select
                      size="small"
                      :dropdown-match-select-width="false"
                      class="my-year-select"
                      :value="String(current.year())"
                      @change="
                  newYear => {
                    onChange(current.year(+newYear));
                  }
                "
                  >
                    <a-select-option
                        v-for="val in getYears(current)"
                        :key="String(val)"
                        class="year-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col>
                  <a-select
                      size="small"
                      :dropdown-match-select-width="false"
                      :value="String(current.month())"
                      @change="
                  selectedMonth => {
                    onChange(current.month(parseInt(String(selectedMonth), 10)));
                  }
                "
                  >
                    <a-select-option
                        v-for="(val, index) in getMonths(current)"
                        :key="String(index)"
                        class="month-item"
                    >
                      {{ val }}
                    </a-select-option>
                  </a-select>
                </a-col>
              </a-row>
            </div>
          </template>

          <template #dateFullCellRender="{ current: value }" v-model="value">
            <a  v-if="getSpecificDayQuestion(value)!=''" :href="'/questionInfo/'+getSpecificDayQuestion(value)" :class="getDateCss(value).value.css" class="tooltip">
                <span v-if="calendarKey==='true'" class="tooltiptext" v-bind:title="getSpecificDayQuestion(value)"></span>
              {{ value.date() }}
            </a>
            <span v-else>{{value.date()}}</span>
          </template>
        </a-calendar>
      </div>

    </div>
  </div>
</template>
<script>
import { usePagination } from 'vue-request';
import {computed, defineComponent, onBeforeMount, onMounted, reactive, ref, watch} from 'vue';
import axios from 'axios';
import {isReturnTrue, reload} from "@/util/util";
import router from "@/router";
import dayjs from "dayjs";


export default defineComponent({
  setup() {
    const removeSelectedType=(name)=>{
      let index=0;
      const r=ref([]);
      for (let i = 0; i < selectedType.value.length; i++) {
        if(name!=selectedType.value[i].name){
          // selectedType.value.splice(i,1)
          // index=i;
          r.value.push(selectedType.value[i])
          console.log(i)
        }
      }
      selectedType=r
      // for (let i = 0; i < selectedType.length; i++) {
      //
      // }
      console.log(selectedType.value)
    }
    let selectedType=ref([])
    const mode = ref('top');
    const types=ref([{
      name:'',
      code:''
    }])
    const getDifficultyColor=(text)=>{
      if(text==='EASY'){
        return "green"
      }
      if(text==='MEDIUM')
      {
        return "yellow"
      }
      return "red"
    }
    const columns = [{
      title: '题目',
      dataIndex: 'title',
      sorter: true,
      width: 'auto',
    }, {
      title: '题解',
      dataIndex: 'solutionNum',
      width: '20%',
    }, {
      title: '通过率',
      dataIndex: 'acRate',
      width: '20%'
    },
      {
        title: '难度',
        dataIndex: 'difficulty',
        width: '20%'
      },
    ];
    const queryData = params => {
      let _datasource=dataSource
      params.types=selectedType.value.length==0?null:selectedType.value.map(item=>item.id)
      params.title=title.value==''?null:title.value
      axios.post("/core/t-question/page",
          params,
      ).then((response)=>{
        if(isReturnTrue(response.data.code)){
          console.log("分页成功");
          _datasource.value=response.data.data.records;
          pagination.value.pageSize=response.data.data.size;
          pagination.value.current=response.data.data.current;
          pagination.value.total=response.data.data.total
          console.log(pagination.value)
          return response.data.data.total;
        }
        else{
          alert(response.data.message);
        }
      });
    };
    // const {
    //   data: dataSource,
    //   run,
    //   loading,
    //   current,
    //   pageSize,
    // } = usePagination(queryData, {
    //     currentKey: 'pageNo',
    //     pageSizeKey: 'pageSize',
    //   },
    // );
    const dataSource=ref([{
      title:'',
      solutionNum:'',
      difficulty:'',
      acRate:'',
      payOnly:'',
      titleSlug:'',
    }])
    // const dataSource=[{
    //   title:'',
    //   solutionNum:'',
    //   difficulty:'',
    //   acRate:'',
    //   payOnly:''
    // }]
    const pagination = ref({
      total: 10,
      current: 1,
      pageSize: 10,
    });
    const handleTableChange = (pag, filters, sorter) => {
      queryData({
        pageSize:pag.pageSize,
        pageNo:pag.current,
        title:title.value,
        types:selectedType.value
      })
      console.log("页切换")
    };
    const activeKey = ref('1');
    const changeType = val => {
      if(selectedType.value.length>0){
        for(let i = 0; i < selectedType.value.length; i++){
          if(selectedType.value[i].code===val){
            selectedType.value.splice(i,1)
            return;
          }
        }
      }
      for (let e of types.value) {
        if(e.code===val){
          console.log(e.name)
          selectedType.value.push({
            code:e.code,
            name:e.name,
            id:e.id
          })
        }
      }
      console.log(selectedType.value);
    };
    const getQuestionInfo=(index)=>{
      console.log("点击题目跳转")
      router.push('/questionInfo/'+dataSource.value[index].titleSlug);
    }
    onMounted(()=>{
      queryData({
        pageSize:10,
        pageNo:1
      });
      getDailyQuestion()
      getAllTypes()
      reload()
    });
    const calendarKey=ref('');
    const dailyQuestions=ref([])
    const getMonthData = value => {
      if (value.month() === 8) {
        return 1394;
      }
    };
    const title = ref();
    const onPanelChange = (value, mode) => {
      console.log(value, mode);
    };
    const getMonths = value => {
      const localeData = value.localeData();
      const months = [];
      for (let i = 0; i < 12; i++) {
        months.push(localeData.monthsShort(value.month(i)));
      }
      return months;
    };
    const getSpecificDayQuestion=(value)=>{
      if(getCurrentMonth()===value.month()+1){
        return dailyQuestion[value.date()-1]===undefined?'':dailyQuestion[value.date()-1].titleSlug
      }
      return ''
    }
    const getCurrentMonth=()=>{
      return dayjs().month() + 1;
    }
    const getYears = value => {
      const year = value.year();
      const years = [];
      for (let i = year - 10; i < year + 10; i += 1) {
        years.push(i);
      }
      return years;
    };
    // 日期样式设置
    const getDateCss =  (val) => {
      const day = val.date();
      const currentMonth = dayjs().month() + 1;
      const month = val.month() + 1;
      const res = ref({
        css: '',
        title: ''
      })
      if (currentMonth != month ) {
        res.value.css="date_work"
        return res
      }
      // res.value.title=dailyQuestion.value[day].titleSlug
      // 如果是周六周日
      if (isDailyFinished(val)) {
        res.value.css = "date_week"
        return res;
      } else {
        res.value.css = "date_work"
        return res;
      }
    };
    let dailyQuestion=reactive([{
      titleSlug:'',
      currentDateTime:'',
      isFinished:false
    }]);
    const isDailyFinished=(value)=>{
      if(getCurrentMonth()===value.month()+1){
        return dailyQuestion[value.date()-1]===undefined?false:dailyQuestion[value.date()-1].isFinished
      }
      return false;
    }
    const getDailyQuestion=async () => {
      await axios.get("/core/t-question/dailyQuestion").then((response) => {
        if (isReturnTrue(response.data.code)) {
          dailyQuestion = response.data.data
          console.log("每日一题")
          calendarKey.value='true'
        } else {
          alert(response.data.message)
        }
      })
      console.log(dailyQuestion)
    }
    const getAllTypes=()=>{
      axios.get("/core/t-question-type/all").then((response)=>{
        if(isReturnTrue(response.data.code)){
          types.value=response.data.data
        }
        else{
          alert(response.data.message)
        }
      })
    }
    const queryDataByCondition=(params)=>{
      queryData(params)
    }
    const checked1=ref(true)
    return {
      changeType,
      types,
      mode,
      activeKey,
      dataSource,
      pagination,
      // loading,
      columns,
      handleTableChange,
      queryData,
      getQuestionInfo,
      title,
      getMonthData,
      onPanelChange,
      getMonths,
      getYears,
      dailyQuestions,
      getDateCss,
      getDailyQuestion,
      dailyQuestion,
      getCurrentMonth,
      getSpecificDayQuestion,
      calendarKey,
      isDailyFinished,
      getDifficultyColor,
      selectedType,
      removeSelectedType,
      queryDataByCondition,
      checked1


    };
  },
});
</script>
<style scoped>
.events {
  max-width: 100%;
  max-height: 100%;
  list-style: none;
  margin: 0;
  padding: 0;
}
.events .ant-badge-status {
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  text-overflow: ellipsis;
  font-size: 12px;
}
.notes-month {
  text-align: center;
  font-size: 28px;
}
.notes-month section {
  max-height: 100%;
  width: 1000px;
  font-size: 28px;
}
</style>
<style>
body {
  font-family: Arial, sans-serif;
  margin: 0;
  padding: 0;
}
.container {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0px;
  position: absolute;
  width: 1200px;
  left: 5%;
  top: 3%;
}
.left-section {
  flex: 1;
  flex-basis: 50%;
  padding: 20px;
  left: 0px;
}
.right-section{
  /*align-self: flex-start;*/
  position: fixed;
  /*top: 100px;*/
  /*flex: 0 0 300px;*/
  /*left: 100%;*/
  top: 100px;
  right: 10%;
  width: 240px;
  /*min-height: 100vh;*/
}
.elevated-box {
  top: 0;
  width: 120%;
  height: 500px;
  background-color: #ffffff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15);
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  padding: 20px;
}
.date {
  position: relative;
  z-index: 2;
  display: inline-block;
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  border-radius: 2px;
  transition: background 0.3s, border 0.3s;
}
.date_week {
  position: relative;
  z-index: 2;
  display: inline-block;
  min-width: 24px;
  height: 24px;
  line-height: 24px;
  border-radius: 2px;
  transition: background 0.3s, border 0.3s;
  background-color: #3ff53f;
}
/*.date_work {*/
/*  position: relative;*/
/*  z-index: 2;*/
/*  display: inline-block;*/
/*  min-width: 24px;*/
/*  height: 24px;*/
/*  line-height: 24px;*/
/*  border-radius: 2px;*/
/*  transition: background 0.3s, border 0.3s;*/
/*  background-color: rgb(20, 134, 228);*/
/*}*/

/* Tooltip 容器 */
.tooltip {
  position: relative;
  /*display: inline-block;*/
  /*border-bottom: 1px dotted black; !* 悬停元素上显示点线 *!*/
}

/* Tooltip 文本 */
.tooltip .tooltiptext {
  visibility: hidden;
  width: 120px;
  /*background-color: black;*/
  color: #fff;
  text-align: center;
  padding: 10px 0;
  border-radius: 20px;
  /* 定位 */
  position: absolute;
  z-index: 1;
}
/* 鼠标移动上去后显示提示框 */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
.red{
  color: red;
}.green{
  color: green;
}.yellow{
  color: brown;
}
</style>